package com.chinasofti.bufferedio;

public class MyBinarySearchDemo {
    public static void main(String[] args) {
        //二分法
        int [] arr = {1,2,3,4,5,6,7,8,9,10};
        int number = 9;
        int i = binarySearch(arr, 2);
        System.out.println("i="+i);
    }
    private  static int binarySearch(int [] arr , int number){
        int min = 0;
        int max = arr.length-1;
        while (min<=max){
            //计算出mid
            int mid = (min+max)>>1;
            if(arr[mid]>number){
                //要查的元素在左边
                max = mid-1;
            }else if(arr[mid]<number){
                min = mid+1;
            }else {
                return  mid;
            }
        }
        return -1;
    }
}
